package com.hightrast.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hightrast.service.api.domain.vo.menu.QueryRastUserMenuVo;
import com.hightrast.service.api.entity.RastRoleMenu;
import com.hightrast.service.mapper.RastRoleMenuMapper;
import com.hightrast.service.service.IRastRoleMenuService;
import com.hightrast.service.util.TreeUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 * @author hx
 * @since 2025-01-11
 */
@Service
public class RastRoleMenuServiceImpl extends ServiceImpl<RastRoleMenuMapper, RastRoleMenu> implements IRastRoleMenuService {

    /**
     * 获取用户角色下的菜单
     * @return
     */
    @Override
    public List<QueryRastUserMenuVo> queryRastRoleMenus(Long userId){

        List<QueryRastUserMenuVo> rastRoleMenus = this.baseMapper.selectUserMenus(userId);

        // 使用通用的树形结构构建方法
        return TreeUtils.buildTree(
                rastRoleMenus,
                QueryRastUserMenuVo::getId,
                QueryRastUserMenuVo::getParentId,
                QueryRastUserMenuVo::getChildren,
                (menu) -> {
                    List<QueryRastUserMenuVo> children = rastRoleMenus.stream()
                            .filter(item -> Objects.equals(item.getParentId(), menu.getId()))
                            .collect(Collectors.toList());
                    menu.setChildren(children);
                    return null;
                }
        );
    }

}
